package com.yc.demo.d0301;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "CookieServlet", value = "/CookieServlet")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //获取cookie数据
        final  Cookie[] cookies = request.getCookies();
        final PrintWriter out = response.getWriter();
        //没有cookied数据，该数组为空
        if (cookies!=null){
            out.printf("<ul>");
            for (Cookie cookie : cookies) {
                out.printf("<li>%s : %s<li>",cookie.getName(),cookie.getValue());
                out.printf("</l>");
            }
        }
        String name = request.getParameter("name");
        //从服务器向浏览器发送cookie数据
        Cookie cookie = new Cookie("name",name);
        if (name == null){
            cookie.setMaxAge(0);
        } else {
          cookie.setMaxAge(60*60*24*7);
        }
        response.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
